<?php

namespace app\api\controller;

use app\api\validate\User as ValidateUser;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\IdExamine;
use fast\Random;
use think\Config;
use think\Validate;
use app\common\library\Auth;
use app\common\library\Token;
use app\common\model\User as ModelUser;
use think\Db;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = [
        'login',
        'register'
    ];

    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }


    /**
     * 会员登录
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }


    /**
     * 注册会员
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     */
    public function register()
    {
        $password = $this->request->post('password');
        $mobile = $this->request->post('mobile');
        $username = $mobile;
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }

        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }

        $ret = $this->auth->register($username, $password, '', $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    //实名认证申请
    public function idExamine()
    {
        $userInfo = $this->auth->getUser();
        if (!empty($userInfo->real_name)) {
            $this->error('当前已实名认证，如要修改请询问工作人员修改');
        }

        $examineInfo = IdExamine::where(['user_id' => $userInfo->id, 'status' => 1])->find();
        if ($examineInfo) {
            $this->error('有已申请的身份证信息，请等待审核人员审核！');
        }
        IdExamine::create([
            'user_id' => $userInfo->id,
            'img1' => $this->request->post('img1'), //身份证正面
            'img2' => $this->request->post('img2'), //身份证反面
            'id_card' => $this->request->post('id_card'), //身份证号码
            'real_name' => $this->request->post('real_name'), //姓名
        ]);
        
        $this->success('申请成功，请等待审核人员审核！');
    }

    /**
     * 重置登陆密码
     * @ApiMethod (POST)
     * @param string $old_password 旧密码
     * @param string $new_password 新密码
     */
    public function resetPwd()
    {
        $user = $this->auth->getUser();

        $password = $this->request->post('new_password');
        $oldPwd = $this->request->post('old_password');


        if (empty($password) || empty($oldPwd)) {
            $this->error('原密码和新密码均不能为空');
        }

        if (md5(md5($oldPwd) . $user->salt) != $user->password) {
            var_dump(md5(md5($oldPwd) . $user->salt), $user->password);
            $this->error('原密码错误');
        }

        $user->salt = Random::alpha();
        $user->password = md5(md5($password) . $user->salt);
        $user->save();
        $this->success('登陆密码修改成功');
    }

    /**
     * 重置支付密码
     * @ApiMethod (POST)
     * @param string $old_pay_password      旧密码
     * @param string $new_pay_password  新密码
     */
    public function resetPayPwd()
    {
        $user = $this->auth->getUser();

        $pay_password = $this->request->post('new_pay_password');
        $oldPayPwd = $this->request->post('old_pay_password');

        if (empty($pay_password) || empty($oldPayPwd)) {
            $this->error('原密码和新密码均不能为空');
        }

        if (!empty($user->pay_pwd) && md5(md5($oldPayPwd)) != $user->pay_pwd) {
            $this->error('支付密码错误');
        }
        $user->pay_pwd = md5(md5($pay_password));
        $user->save();
        $this->success('支付密码修改成功');
    }

    /**
     * 用户绑定银行卡接口
     */
    public function addCard()
    {
        $user = $this->auth->getUser();

        $cardname = $this->request->post('card_name'); //持卡人
        $bankNum = $this->request->post('bank_num');  //银行卡号
        $bankSubName = $this->request->post('bank_sub_name'); //支行名称
        $bankName = $this->request->post('bank_name');  //银行名称
        $payPwd = $this->request->post('pay_pwd');  //支付密码

        if (empty($cardname) || empty($bankNum) || empty($bankSubName) || empty($bankName) || empty($payPwd)) {
            $this->error('缺少必要的数据');
            exit;
        }
        // 判断持卡人是否重复
        $exists = Db::name('user')
            ->where('card_name', $cardname)
            ->where('id', '<>', $user->id)
            ->find();
        if ($exists) {
            return $this->error(__('持卡人已经存在'));
        }

        // 3. 插入数据
        $data = [
            'card_name' => $cardname,
            'bank_num' => $bankNum,
            'bank_sub_name' => $bankSubName,
            'bank_name' => $bankName,
            'pay_pwd'   => md5(md5($payPwd)),
            'updatetime' => time()
        ];

        $rows = Db::name('user')->where('id', $user->id)->update($data);
        if ($rows) {
            $this->success('绑定成功');
        } else {
            $this->error('绑定失败');
        }
    }

    /**
     * 银行卡编辑接口
     */
    public function editCard()
    {
        $user = $this->auth->getUser();
        $cardname = $this->request->post('card_name'); //持卡人
        $bankNum = $this->request->post('bank_num');  //银行卡号
        $bankSubName = $this->request->post('bank_sub_name'); //支行名称
        $bankName = $this->request->post('bank_name');  //银行名称
        $payPwd = $this->request->post('pay_pwd');  //支付密码

        if (empty($cardname) || empty($bankNum) || empty($bankSubName) || empty($bankName) || empty($payPwd)) {
            $this->error('缺少必要的数据');
            exit;
        }
        // 判断持卡人是否重复
        $exists = \app\common\model\User::where('card_name', $cardname)
            ->where('id', '<>', $user->id)
            ->find();
        if ($exists) {
            $this->error(__('持卡人已经存在'));
        }

        $data = [
            'card_name' => $cardname,
            'bank_num' => $bankNum,
            'bank_sub_name' => $bankSubName,
            'bank_name' => $bankName,
            'pay_pwd'   => md5(md5($payPwd)),
            'updatetime' => time()
        ];

        $rows = Db::name('user')->where('id', $user->id)->update($data);
        if ($rows) {
            $this->success('修改成功');
        } else {
            $this->error('修改失败');
        }
    }

    /**
     * 查询银行卡信息
     */
    public function showCard()
    {
        $user = $this->auth->getUser();

        $rows = Db::name('user')
            ->field('card_name,nickname,bank_num,bank_sub_name,bank_name,pay_pwd')
            ->where('id', $user->id)
            ->find();

        if ($rows) {
            $rows['bank_num'] = showNumberByXing($rows['bank_num']);
            $this->success('查询成功', $rows);
        } else {
            $this->error('绑定失败');
        }
    }

   /**
     * 查询实名验证信息
     */
    public function realname()
    {
        $user = $this->auth->getUser();
  
        $rows = Db::name('id_examine')
            ->field('img1,img2,id_card,real_name')
            ->where('user_id', $user->id)
            ->find();
        if( $rows ){
            $rows['id_card'] = showNumberByXing($rows['id_card']);
        }
    
        $this->success('查询成功', $rows);
    }

    /**
     * 查询用户个人信息
     */
    public function info()
    {
        $user = $this->auth->getUser();

        if( $this->request->isPost() ){
            $post = $this->request->post();
            $validate = new ValidateUser();
            if( !$validate->check($post) ){
                $this->error($validate->getError());
            }
            $user = ModelUser::get($user->id);
            if($user->save($post)){
                $this->success('修改成功');
            }else{
                $this->error($user->getError());
            }
            
        }

        $rows = Db::name('user')
                ->field('nickname,avatar,mobile')
                ->where('id', $user->id)
                ->find();

        if(empty($rows['avatar'])){
            $rows['avatar'] = config('host') . 'assets/img/user.png';
        }

        $this->success('查询成功', $rows);
    }


}
